package com.example.vsftpd;

import com.example.vsftpd.util.RunProcessUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 修改用户密码
 * @author yangjl
 */
@Controller
@RequestMapping("/repwd")
public class ResetPwdController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String pwdFilePath = "/etc/vsftpd/virtusers";

    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        String seCode = UUID.randomUUID().toString();
        request.setAttribute("seCode", seCode);
        request.getSession().setAttribute("seCode", seCode);
        return "repwd";
    }

    /**
     * 执行更新密码动作
     * @param uname
     * @param oldPwd
     * @param newPwd
     * @param seCode
     * @param request
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String rePasswd(String uname, String oldPwd, String newPwd,
                           String seCode, HttpServletRequest request){
        Assert.hasText(seCode, "forbid.");
        try {
            String seCode1 = (String)request.getSession().getAttribute("seCode");
            if(seCode.equals(seCode1)){
                rePwd(uname, oldPwd, newPwd);
                request.getSession().setAttribute("seCode", null);
                return "0";
            }else {
                request.getSession().setAttribute("seCode", null);
                return "非法访问。";

            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error: "+e.getMessage();
        }

    }

    private synchronized void rePwd(String uname, String oldPwd, String newPwd) throws IOException {

        Assert.hasText(uname, "user name must be has value.");
        Assert.hasText(oldPwd, "old pwd must be has value.");
        Assert.hasText(newPwd, "new pwd must be has value.");
        File pwdFile = new File(pwdFilePath);
        if(pwdFile.exists()){
            boolean isSuccess = false;
            List<String> lines = FileUtils.readLines(pwdFile, "utf-8");
            for(int i=0;i<lines.size();i++){
                String unameLine = lines.get(i);
                if(unameLine.equalsIgnoreCase(uname)){
                    String pwd = lines.get(i+1);//当前密码
                    if(oldPwd.equals(pwd)){
                        lines.set(i+1, newPwd);
                        isSuccess = true;
                    }
                    break;
                }
            }

            if(isSuccess){

                FileUtils.writeLines(pwdFile, lines);
//        pwds.stream().filter(pwd->{pwd.equalsIgnoreCase("")}).

                String[] cmds2 = { "sh", "-c", "db_load -T -t hash -f /etc/vsftpd/virtusers /etc/vsftpd/virtusers.db" };
                Map<String, String> responseMap = RunProcessUtils.execSimpleCmd("./", cmds2);
                String code = responseMap.get("code");
                String msg = responseMap.get("msg");
                if("0".equals(code)) {
                    logger.debug("更新密码文件库成功！");
                }else {
                    logger.error("更新密码文件失败! {}", msg);
                    throw new RuntimeException(msg);
                }
            }else {
                String msg = "修改失败：用户名或原密码不正确！";
                logger.error("{}", msg);
                throw new RuntimeException(msg);
            }
        }
    }
}
